using System.Globalization;
using LinqToDB.Tools;

namespace NalogGarLoader.Model.GarRepositoryReader;
public class GarDirectoryRepositoryReader : GarRepositoryReader
{
    public GarDirectoryRepositoryReader(string sourcePath, HashSet<string> tableImportSet) 
        : base(sourcePath, tableImportSet)
    {        
    }

    protected override void ReadGarVersion()
    {
        string versionFileName = Path.Combine(this.SourcePath, "version.txt");

        if (!File.Exists(versionFileName))
            return;

        using FileStream fs = File.OpenRead(versionFileName);
        using StreamReader sr = new(fs);

        if (DateOnly.TryParse(sr.ReadLine()?.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly parsedDateOnly))
            this.GarVersion = parsedDateOnly;
    }

    public override IEnumerator<GarRepositoryEntry> GetEnumerator()
    {
        foreach (string fileName in Directory.EnumerateFiles(this.SourcePath, "*.xml"))
        {
            string? garType = this.ParseGarType(fileName);

            if (string.IsNullOrEmpty(garType) || ! this.TableImportSet.Contains(garType))
                continue;

            yield return new GarRepositoryEntry(
                fileName,
                this.GarVersion,
                this.ParseGarType(fileName)!,
                this.GetFileStream
                );
        }

        foreach (string dir in Directory.EnumerateDirectories(this.SourcePath))
        {            
            foreach (string fileName in Directory.EnumerateFiles(dir, "*.xml"))
            {
                string? garType = this.ParseGarType(fileName);

                if (string.IsNullOrEmpty(garType) || ! this.TableImportSet.Contains(garType))
                    continue;

            yield return new GarRepositoryEntry(
                fileName,
                this.GarVersion,
                this.ParseGarType(fileName)!,
                this.GetFileStream,
                Path.GetDirectoryName(fileName)!.Split(Path.DirectorySeparatorChar).Last()
                );
            }
        }
    }

    protected override Stream GetFileStream(GarRepositoryEntry garRepositoryEntry)
    {
        return File.OpenRead(garRepositoryEntry.FullFileName);
    }
}